<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card shadow="never" class="search-wrapper">
      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item label="车主姓名" prop="name">
          <el-input v-model="queryParams.name" placeholder="请输入车主姓名" clearable style="width: 200px" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="queryParams.sex" placeholder="请选择性别" clearable style="width: 200px">
            <el-option label="男" value="M" />
            <el-option label="女" value="F" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 操作区域 -->
    <el-card shadow="never" class="table-wrapper">
      <template #header>
        <div class="card-header">
          <div class="left">
            <el-button type="primary" icon="Plus" @click="handleAdd">新增车主</el-button>
            <el-button type="danger" icon="Delete" :disabled="selectedRows.length === 0" @click="handleBatchDelete">批量删除</el-button>
          </div>
        </div>
      </template>
      
      <!-- 车主表格 -->
      <el-table
        v-loading="loading"
        :data="ownerList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="ID" prop="ownerId" width="80" align="center" />
        <el-table-column label="姓名" prop="name" :show-overflow-tooltip="true" />
        <el-table-column label="年龄" prop="age" width="80" align="center" />
        <el-table-column label="身高(cm)" prop="height" width="100" align="center" />
        <el-table-column label="性别" prop="sex" width="80" align="center">
          <template #default="scope">
            {{ scope.row.sex === 'M' ? '男' : '女' }}
          </template>
        </el-table-column>
        <el-table-column label="出生日期" prop="birth" width="120" align="center" />
        <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" @click="handleView(scope.row)">查看</el-button>
            <el-button link type="primary" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button link type="primary" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    
    <!-- 添加或修改车主对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="form.age" :min="0" :max="150" controls-position="right" style="width: 100%" />
        </el-form-item>
        <el-form-item label="身高" prop="height">
          <el-input-number v-model="form.height" :min="0" :max="300" :precision="1" controls-position="right" style="width: 100%" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="form.sex">
            <el-radio label="M">男</el-radio>
            <el-radio label="F">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="出生日期" prop="birth">
          <el-date-picker
            v-model="form.birth"
            type="date"
            placeholder="选择出生日期"
            style="width: 100%"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 查看车主对话框 -->
    <el-dialog title="查看车主详情" v-model="viewOpen" width="500px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="ID">{{ viewForm.ownerId }}</el-descriptions-item>
        <el-descriptions-item label="姓名">{{ viewForm.name }}</el-descriptions-item>
        <el-descriptions-item label="年龄">{{ viewForm.age }}</el-descriptions-item>
        <el-descriptions-item label="身高">{{ viewForm.height }}cm</el-descriptions-item>
        <el-descriptions-item label="性别">{{ viewForm.sex === 'M' ? '男' : '女' }}</el-descriptions-item>
        <el-descriptions-item label="出生日期">{{ viewForm.birth }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Pagination from '@/components/Pagination/index.vue'
import { listCarOwner, getCarOwner, addCarOwner, updateCarOwner, deleteCarOwner, batchDeleteCarOwner } from '@/api/carOwner'

// 加载状态
const loading = ref(false)

// 选中数组
const selectedRows = ref([])

// 总条数
const total = ref(0)

// 车主表格数据
const ownerList = ref([])

// 弹出层标题
const title = ref('')

// 是否显示弹出层
const open = ref(false)
const viewOpen = ref(false)

// 表单引用
const formRef = ref(null)

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: '',
  sex: ''
})

// 表单参数
const form = reactive({
  ownerId: null,
  name: '',
  age: 0,
  height: 0,
  birth: '',
  sex: 'M'
})

// 查看表单
const viewForm = reactive({})

// 表单校验规则
const rules = {
  name: [
    { required: true, message: '姓名不能为空', trigger: 'blur' }
  ],
  age: [
    { required: true, message: '年龄不能为空', trigger: 'blur' }
  ],
  height: [
    { required: true, message: '身高不能为空', trigger: 'blur' }
  ],
  sex: [
    { required: true, message: '性别不能为空', trigger: 'change' }
  ],
  birth: [
    { required: true, message: '出生日期不能为空', trigger: 'change' }
  ]
}

// 在组件挂载时获取数据
onMounted(() => {
  getList()
})

// 获取车主列表
function getList() {
  loading.value = true
  listCarOwner(queryParams).then(response => {
    console.log('获取车主列表响应:', response)
    // 处理后端返回的数据
    if (Array.isArray(response)) {
      // 如果直接返回数组
      ownerList.value = response
      total.value = response.length
    } else if (response && Array.isArray(response.data)) {
      // 如果返回包含data字段的对象
      ownerList.value = response.data
      total.value = response.data.length
    } else if (response && typeof response === 'object') {
      // 如果返回其他对象格式
      ownerList.value = [response]
      total.value = 1
    } else {
      // 如果都不是，设为空数组
      ownerList.value = []
      total.value = 0
      console.error('API返回的数据格式不正确:', response)
    }
    loading.value = false
  }).catch(error => {
    console.error('获取数据失败:', error)
    ownerList.value = []
    total.value = 0
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.ownerId = null
  form.name = ''
  form.age = 0
  form.height = 0
  form.birth = ''
  form.sex = 'M'
  formRef.value?.resetFields()
}

// 搜索按钮操作
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮操作
function resetQuery() {
  queryParams.name = ''
  queryParams.sex = ''
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  selectedRows.value = selection
}

// 新增按钮操作
function handleAdd() {
  reset()
  open.value = true
  title.value = '添加车主'
}

// 修改按钮操作
function handleUpdate(row) {
  reset()
  const ownerId = row.ownerId
  console.log('获取车主详情, ID:', ownerId)
  getCarOwner(ownerId).then(response => {
    console.log('获取车主详情响应:', response)
    // 处理后端返回的数据
    let ownerData = response
    if (response && response.data) {
      ownerData = response.data
    }
    
    if (ownerData) {
      Object.assign(form, ownerData)
      open.value = true
      title.value = '修改车主'
    }
  }).catch(error => {
    console.error('获取车主详情失败:', error)
  })
}

// 查看按钮操作
function handleView(row) {
  const ownerId = row.ownerId
  console.log('查看车主详情, ID:', ownerId)
  getCarOwner(ownerId).then(response => {
    console.log('获取车主详情响应:', response)
    // 处理后端返回的数据
    let ownerData = response
    if (response && response.data) {
      ownerData = response.data
    }
    
    if (ownerData) {
      Object.assign(viewForm, ownerData)
      viewOpen.value = true
    }
  }).catch(error => {
    console.error('获取车主详情失败:', error)
  })
}

// 删除按钮操作
function handleDelete(row) {
  const ownerId = row.ownerId
  ElMessageBox.confirm('是否确认删除车主编号为"' + ownerId + '"的数据项?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteCarOwner(ownerId).then(() => {
      getList()
      ElMessage.success('删除成功')
    })
  })
}

// 批量删除按钮操作
function handleBatchDelete() {
  const ownerIds = selectedRows.value.map(row => row.ownerId).join(',')
  ElMessageBox.confirm('是否确认删除车主编号为"' + ownerIds + '"的数据项?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    batchDeleteCarOwner(ownerIds).then(() => {
      getList()
      ElMessage.success('删除成功')
    })
  })
}

// 表单提交
function submitForm() {
  formRef.value?.validate(valid => {
    if (valid) {
      if (form.ownerId) {
        updateCarOwner(form).then(() => {
          ElMessage.success('修改成功')
          open.value = false
          getList()
        })
      } else {
        addCarOwner(form).then(() => {
          ElMessage.success('新增成功')
          open.value = false
          getList()
        })
      }
    }
  })
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.search-wrapper {
  margin-bottom: 20px;
}

.table-wrapper {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .left {
      display: flex;
      gap: 10px;
    }
  }
}
</style> 